package com.xiaoge.basedevlibrary.http;

import com.xiaoge.basedevlibrary.utils.JsonUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.Map;

public class HttpUtils {

    private volatile static HttpUtils instance;

    /**
     * Double Check 单例模式
     *
     * @return
     */
    public static HttpUtils getInstance() {
        if (instance == null) {
            synchronized (HttpUtils.class) {
                if (instance == null) {
                    instance = new HttpUtils();
                }
            }
        }
        return instance;
    }

    /**
     * 网络请求的接口回调监听器
     */
    public interface NetResponseListener {
        void onSuccess(GuoBaseResponseBean response, int requestCode);

        void onFailed(int requestCode);
    }

    /**
     * 文件下载的接口回调监听器
     */
    public interface NetDownLoadFileListener extends NetResponseListener {

        void onSuccess(File response, int requestCode);

        void onLoading(long current, boolean isDownloading, int requestCode);
    }

    /**
     * 文件上传的接口回调监听
     */
    public interface NetUpLoadFileListener extends NetResponseListener {
        void onLoading(long current, boolean isDownloading, int requestCode);
    }


    /**
     * 异步get请求
     *
     * @param url
     * @param maps
     * @param requestCode
     * @param clazz
     * @param listener
     * @return
     */
    public Callback.Cancelable get(String url, Map<String, String> maps, final int requestCode, final Class<? extends GuoBaseResponseBean> clazz, final NetResponseListener listener) {
        RequestParams params = new RequestParams(url);
        if (maps != null && !maps.isEmpty()) {
            for (Map.Entry<String, String> entry : maps.entrySet()) {
                params.addQueryStringParameter(entry.getKey(), entry.getValue());
            }
        }

        Callback.Cancelable cancelable = x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                GuoBaseResponseBean guoBaseResponseBean = JsonUtils.json2Object(result, clazz);//按正常响应解析
                listener.onSuccess(guoBaseResponseBean, requestCode);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                listener.onFailed(requestCode);
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {

            }
        });
        return cancelable;
    }

    /**
     * 带缓存的异步get请求
     *
     * @param url
     * @param maps
     * @param requestCode
     * @param clazz
     * @param listener
     * @return
     */
    public Callback.Cancelable getCache(String url, Map<String, String> maps, final int requestCode, final Class<? extends GuoBaseResponseBean> clazz, final NetResponseListener listener) {
        RequestParams params = new RequestParams(url);
        if (maps != null && !maps.isEmpty()) {
            for (Map.Entry<String, String> entry : maps.entrySet()) {
                params.addQueryStringParameter(entry.getKey(), entry.getValue());
            }
        }

        // 默认缓存存活时间, 单位:毫秒（如果服务器没有返回有效的max-age或Expires则参考）
        params.setCacheMaxAge(1000 * 60);//设置缓存当这个缓存事件过了的时候, 这时候就会不走这个onCache方法, 直接发起网络请求,
        Callback.Cancelable cancelable = x.http().get(params, new Callback.CacheCallback<String>() {
            @Override
            public boolean onCache(String result) {
                GuoBaseResponseBean guoBaseResponseBean = JsonUtils.json2Object(result, clazz);//按正常响应解析
                listener.onSuccess(guoBaseResponseBean, requestCode);
                return true;//这里返回一个true, 就是走了cache就不再发起网络请求了, 返回一个false, 就是不信任缓存数据, 再次发起网络请求
            }

            @Override
            public void onSuccess(String result) {
                if (result != null) {
                    //如果走了cache方法返回了true, 将不再发起网络请求, 这里拿到的result就是null,
                    GuoBaseResponseBean guoBaseResponseBean = JsonUtils.json2Object(result, clazz);//按正常响应解析
                    listener.onSuccess(guoBaseResponseBean, requestCode);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                listener.onFailed(requestCode);
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
        return cancelable;
    }

    /**
     * 异步post请求
     *
     * @param url
     * @param maps
     * @param requestCode
     * @param clazz
     * @param listener
     * @return
     */
    public Callback.Cancelable post(String url, Map<String, String> maps, final int requestCode, final Class<? extends GuoBaseResponseBean> clazz, final NetResponseListener listener) {
        RequestParams params = new RequestParams(url);
        if (maps != null && !maps.isEmpty()) {
            for (Map.Entry<String, String> entry : maps.entrySet()) {
                params.addBodyParameter(entry.getKey(), entry.getValue());
            }
        }

        Callback.Cancelable post = x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                GuoBaseResponseBean guoBaseResponseBean = JsonUtils.json2Object(result, clazz);//按正常响应解析
                listener.onSuccess(guoBaseResponseBean, requestCode);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                listener.onFailed(requestCode);
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {

            }
        });
        return post;
    }


    /**
     * 文件上传
     *
     * @param url
     * @param maps
     * @param file
     * @param requestCode
     * @param clazz
     * @param listener
     * @return
     */
    public Callback.Cancelable upLoadFile(String url, Map<String, String> maps, Map<String, File> file, final int requestCode, final Class<? extends GuoBaseResponseBean> clazz, final NetUpLoadFileListener listener) {
        RequestParams params = new RequestParams(url);
        if (maps != null && !maps.isEmpty()) {
            for (Map.Entry<String, String> entry : maps.entrySet()) {
                params.addBodyParameter(entry.getKey(), entry.getValue());
            }
        }
        if (file != null && !maps.isEmpty()) {
            for (Map.Entry<String, File> entry : file.entrySet()) {
                params.addBodyParameter(entry.getKey(), entry.getValue().getAbsoluteFile());
            }
        }
        // 有上传文件时使用multipart表单, 否则上传原始文件流.
        params.setMultipart(true);//这个是标示上传的文件内容的,
        Callback.Cancelable cancelable = x.http().post(params, new Callback.ProgressCallback<String>() {

            @Override
            public void onSuccess(String result) {
                GuoBaseResponseBean guoBaseResponseBean = JsonUtils.json2Object(result, clazz);//按正常响应解析
                listener.onSuccess(guoBaseResponseBean, requestCode);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                listener.onFailed(requestCode);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }

            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                listener.onLoading(current, isDownloading, requestCode);
            }
        });

        return cancelable;
    }

    /**
     * 文件下载
     *
     * @param url
     * @param filepath
     * @param requestCode
     * @param listener
     */
    public void downLoadFile(String url, String filepath, final int requestCode, final NetDownLoadFileListener listener) {

        RequestParams params = new RequestParams(url);
        params.setAutoRename(true);// 断点续传, 也就是说支持中断之后再继续下载,
        params.setSaveFilePath(filepath);//设置文件保存的路径
        x.http().post(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onSuccess(final File result) {
                listener.onSuccess(result, requestCode);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                listener.onFailed(requestCode);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }

            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(final long total, final long current, final boolean isDownloading) {
                listener.onLoading(current, isDownloading, requestCode);
            }
        });
    }
}